package com.aq.appserver.server.account.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aq.appserver.common.bean.BaseResp;
import com.aq.appserver.common.bean.PageBean;
import com.aq.appserver.common.bean.Request;
import com.aq.appserver.common.util.AccountType;
import com.aq.appserver.common.util.CommonUtil;
import com.aq.appserver.common.util.PWDUtil;
import com.aq.appserver.server.account.bean.AccountBean;
import com.aq.appserver.server.account.bean.AccountBeanPad;
import com.aq.appserver.server.account.bean.AccountBeanWeb;
import com.aq.appserver.server.account.entity.Account;
import com.aq.appserver.server.account.entity.Feather;
import com.aq.appserver.server.account.entity.HeadImg;
import com.aq.appserver.server.account.service.AccountService;
import com.aq.appserver.server.theme.service.ThemeService;

@Controller
@RequestMapping("/account")
public class AccountController {
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private ThemeService themeService;

	@RequestMapping("/register")
	@ResponseBody
	public Object register(@RequestBody Account account) {
		BaseResp response = new BaseResp();
		Account accoutInfo = accountService.findByPhoneNumber(account.getPhoneNumber());
		if (accoutInfo != null) {
			response.setResp("9999", "该手机号码已经被注册。");
		} else {
			account.setPassword(PWDUtil.GetMD5Code(account.getPassword()));
			account.setUpdateTime(new Date());
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			account.setRegisterTime(sd.format(new Date()));
			//初始化羽毛值为10个
			account.setFeather(10);
			account.setSpeakState("0");
			accountService.save(account);
			
			//根据用户名密码查询用户其他信息
			AccountBean accountBean = new AccountBean();
			accountBean.setLoginName(account.getPhoneNumber());
			accountBean.setPassword(PWDUtil.GetMD5Code(account.getPassword()));
			Account accountInfo = accountService.findByPhoneNumber(account.getPhoneNumber());
			accountInfo.setMyHelpCount(0);
			accountInfo.setMyReplyCount(0);
			String honour = CommonUtil.covertFeatherNoToHonour(0);
			accountInfo.setHonour(honour);
			response.put("accountInfo", accountInfo);
		}
		return response;
	}
	
	@RequestMapping("/checkAcct")
	@ResponseBody
	public Object checkAcct(@RequestBody Account account) {
		BaseResp response = new BaseResp();
		Account accoutInfo = accountService.findByPhoneNumber(account.getPhoneNumber());
		if (accoutInfo != null) {
			response.setResp("9999", "该手机号码已经被注册。");
		}
		return response;
	}
	
	@RequestMapping("/login")
	@ResponseBody
	public Object login(@RequestBody AccountBean accountBean) {
		BaseResp response = new BaseResp();	
		
		//判断是否是通过第三方账号登录
		AccountBeanPad accoutInfo = null;
		String uuid = accountBean.getUuid();
		
		if (!StringUtils.isEmpty(uuid)) {
			String loginName = accountBean.getLoginName();
			String accountType = accountBean.getAccountType();
			if (StringUtils.isEmpty(loginName)) {
				//非一次用第三方账号登录，直接根据UUID查询账号信息
				if (AccountType.QQ_LOGIN.equals(accountType)) {
					accoutInfo = accountService.findByQqUuid(uuid);
				} else if (AccountType.WX_LOGIN.equals(accountType)) {
					accoutInfo = accountService.findByWxUuid(uuid);
				} else {
					accoutInfo = accountService.findByWbUuid(uuid);
				}
			} else {
				//第一次用第三方账号登录，需要绑定账号
				accountBean.setPassword(PWDUtil.GetMD5Code(accountBean.getPassword()));
				accoutInfo = accountService.findByPhoneNumberAndPassword(accountBean);
				if (accoutInfo != null) {
					if (AccountType.QQ_LOGIN.equals(accountType)) {
						accountService.updateQqUuidByLoginName(loginName, uuid);
					} else if (AccountType.WX_LOGIN.equals(accountType)) {
						accountService.updateWxUuidByLoginName(loginName, uuid);
					} else {
						accountService.updateWbUuidByLoginName(loginName, uuid);
					}
				}
			}
		} else {
			accountBean.setPassword(PWDUtil.GetMD5Code(accountBean.getPassword()));
			accoutInfo = accountService.findByPhoneNumberAndPassword(accountBean);
		}
		
		if (accoutInfo == null) {
			response.setResp("9999", "用户名或密码不正确。");
		} else {
			//处理用户信息，新增荣誉、我发过的求助数，我参与的求助数
			int myHelpCount = themeService.getMyHelpCount(accoutInfo.getPhoneNumber());
			accoutInfo.setMyHelpCount(myHelpCount);
			
			int myReplyCount = themeService.getMyReplyCount(accoutInfo.getPhoneNumber());
			accoutInfo.setMyReplyCount(myReplyCount);
			
			String honour = CommonUtil.covertFeatherNoToHonour(myHelpCount + myReplyCount);
			accoutInfo.setHonour(honour);
			response.put("account", accoutInfo);
		}
		
		return response;
	}
	
	@RequestMapping("/queryAccountListWeb")
	@ResponseBody
	public Object queryAccountListWeb(@ModelAttribute("accountBean") AccountBean accountBean, HttpServletRequest request) {
		Map<String, Object> response = new HashMap<String, Object>();
		Pageable pageable = new PageRequest(accountBean.getPage() - 1, accountBean.getRows(), new Sort(Direction.ASC, "id"));
		List<AccountBean> rows = accountService.queryAccountListWeb(accountBean, pageable);
		response.put("rows", rows);
		response.put("total", accountService.queryAccountListWebCount(accountBean));
		return response;
	}
	
	@RequestMapping("/resetPwdWeb")
	@ResponseBody
	public Object resetPwdWeb(@ModelAttribute("accountBean") AccountBean accountBean) {
		BaseResp response = new BaseResp();	
		accountService.resetPwdWeb(accountBean);
		return response;
	}
	
	@RequestMapping("/updateSpeakWeb")
	@ResponseBody
	public Object updateSpeakWeb(@ModelAttribute("accountBean") AccountBean accountBean) {
		BaseResp response = new BaseResp();	
		accountService.updateSpeakState(accountBean);
		return response;
	}
	
	@RequestMapping("/addAccount")
	@ResponseBody
	public Object addAccount(@ModelAttribute("accountBean") AccountBean accountBean, HttpServletRequest request) {
		Map<String, Object> response = new HashMap<String, Object>();
		
		return response;
	}
	
	@RequestMapping("/modAccount")
	@ResponseBody
	public Object modAccount(@ModelAttribute("accountBean") AccountBean accountBean, HttpServletRequest request) {
		Map<String, Object> response = new HashMap<String, Object>();
		accountService.updateAccFeather(accountBean.getPhoneNum(), accountBean.getFeatherNum());
		response.put("flag", 0);
		return response;
	}
	
	@RequestMapping("/delAccount")
	@ResponseBody
	public Object delAccount(@ModelAttribute("accountBean") AccountBean accountBean, HttpServletRequest request) {
		Map<String, Object> response = new HashMap<String, Object>();
		return response;
	}
	
	/**
	 * 保存用户头像信息
	 * @param headImg 头像信息
	 * @return Object 返回信息
	 */
	@RequestMapping("/saveHeadImg")
	@ResponseBody
	public Object saveHeadImg(@RequestBody HeadImg headImg) {
		BaseResp response = new BaseResp();	
		accountService.saveHeadImg(headImg);
		return response;
	}
	
	@RequestMapping("/updateHeadImg")
	@ResponseBody
	public Object updateHeadImg(@RequestBody HeadImg headImg) {
		BaseResp response = new BaseResp();	
		accountService.updateHeadImg(headImg);
		return response;
	}
	
	@RequestMapping("/queryAccountList")
	@ResponseBody
	public Object queryAccountList(@RequestBody Request<Map<String, Object>> request) {
		BaseResp response = new BaseResp();	
		Map<String, Object> condition = request.getParameter();
		PageBean pageBean = request.getPageBean();
		Pageable pageable = new PageRequest(pageBean.getCurrentPage() - 1, pageBean.getPageSize(), new Sort(Direction.DESC, "id"));
		String accCondition = condition.get("condition") == null ? "" : condition.get("condition").toString();
		Page<AccountBeanWeb> accountList = accountService.queryAccountList(accCondition, pageable);
		response.put("rows", accountList.getContent());
		response.put("total", accountList.getTotalElements());
		return response;
	}
	
	/**
	 * 用户禁言和恢复发言
	 * @param 
	 * @return
	 */
	@RequestMapping("/updateSpeakState")
	@ResponseBody
	public Object updateSpeakState(@RequestBody AccountBean accountBean) {
		BaseResp response = new BaseResp();	
		accountService.updateSpeakState(accountBean);
		return response;
	}
	
	/**
	 * 管理员为用户添加羽毛
	 * @param 
	 * @return
	 */
	@RequestMapping("/updateFeather")
	@ResponseBody
	public Object updateFeather(@RequestBody AccountBean accountBean) {
		BaseResp response = new BaseResp();
		String phoneNum = accountBean.getPhoneNum();
		if (StringUtils.isEmpty(phoneNum)){
			response.setResp("9999", "the param of mobile is null.");
			return response;
		}
		int count = Integer.valueOf(accountBean.getFeatherNum());
		synchronized (this) {
			Feather feather = accountService.findByPhoneNum(phoneNum);
			if (feather != null) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				String nowDate = format.format(new Date());
				if (nowDate.equals(feather.getUpdateTime().toString().substring(0,10))) {
					if (feather.getCount() < 30) {
						accountService.updateFeather(phoneNum, feather.getCount() + count , new Date());
						accountService.updateAccFeather(phoneNum, count);
					} else{
						response.setResp("9999", "已达到给用户增加羽毛的上限30.");
					}
				} else {
					accountService.updateFeather(phoneNum, Integer.valueOf(accountBean.getFeatherNum()), new Date());
					accountService.updateAccFeather(phoneNum, count);
				}
			} else {
				Feather featherInfo = new Feather();
				featherInfo.setCount(count);
				featherInfo.setPhoneNum(phoneNum);
				featherInfo.setUpdateTime(new Date());
				accountService.saveFeather(featherInfo);
				accountService.updateAccFeather(phoneNum, count);
			}
		}
		return response;
	}
	
	@RequestMapping("/updateNickName")
	@ResponseBody
	public Object updateNickName(@RequestBody AccountBeanPad accountBeanPad) {
		BaseResp response = new BaseResp();	
		accountService.updateNickName(accountBeanPad);
		return response;
	}
	 
	@RequestMapping("queryAccountInfoList")
    @ResponseBody
	public Object queryAccountInfoList(@RequestBody Request<Map<String, Object>> request) {
		BaseResp resp = new BaseResp();
		PageBean pageBean = request.getPageBean();
		Pageable pageable = new PageRequest(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
		Page<AccountBeanPad>  accountList = accountService.queryAccountInfoList(pageable);
		List<AccountBeanPad> list= accountList.getContent();
		List<AccountBeanPad> accounInfoList = new ArrayList<AccountBeanPad>();
		if (list != null && list.size() > 0) {
			accounInfoList.addAll(list);
			for (AccountBeanPad account : accounInfoList) {
				int myHelpCount = themeService.getMyHelpCount(account.getPhoneNumber());
				account.setMyHelpCount(myHelpCount);
				
				int myReplyCount = themeService.getMyReplyCount(account.getPhoneNumber());
				account.setMyReplyCount(myReplyCount);
			}
			
			Collections.sort(accounInfoList, new Comparator<AccountBeanPad>() {
	            public int compare(AccountBeanPad obj1, AccountBeanPad obj2) {
	                return obj1.getMyReplyCount() - obj2.getMyReplyCount() > 0 ? -1 : 1;
	            }
		    });
		}
		resp.put("accountList", accounInfoList);
		return resp;
    }
				
	@RequestMapping("/updatePWD")
	@ResponseBody
	public Object updatePWD(@RequestBody AccountBean accountBean) {
		BaseResp response = new BaseResp();
		if (StringUtils.isEmpty(accountBean.getNewPassword())) {
			response.setResp("9999", "新密码不能为空");
			return response;    
		}
		
		accountBean.setPassword(PWDUtil.GetMD5Code(accountBean.getPassword()));
		AccountBeanPad accoutInfo = accountService.findByPhoneNumberAndPassword(accountBean);
		if (accoutInfo == null) {
			response.setResp("9999", "修改密码失败，用户名或密码不正确。");
		} else {
			accoutInfo.setPassword(PWDUtil.GetMD5Code(accountBean.getNewPassword()));
			accoutInfo.setUpdateTime(new Date());
			accountService.updatePWD(accoutInfo);
		}
		return response;
	}
}
